package com.wanghlme.exercise05.web;

import com.wanghlme.exercise05.pojo.Emp;
import com.wanghlme.exercise05.service.IEmpService;
import com.wanghlme.exercise05.service.impl.EmpServiceImpl;
import com.wanghlme.exercise05.util.MD5;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@WebServlet("/saveEmp")
public class SaveEmpAction extends HttpServlet {
    private IEmpService empService;

    public SaveEmpAction() {
        empService = new EmpServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String empId = req.getParameter("empId");
        String empName = req.getParameter("empName");
        String empLogin = req.getParameter("empLogin");
        String empPwd = req.getParameter("empPwd");
        String empAge = req.getParameter("empAge");
        String hiredate = req.getParameter("hiredate");
        Emp emp = new Emp();
        emp.setEmpId(Objects.equals(empId, "") ? null : Integer.parseInt(empId));
        emp.setEmpAge(Integer.parseInt(empAge));
        emp.setEmpLogin(empLogin);
        emp.setEmpName(empName);
        emp.setEmpPwd(MD5.enctypeMD5(empPwd));
        Date date = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = format.parse(hiredate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        emp.setEmpHiredate(date);
        int result = empService.saveEmp(emp);
        if (result > 0) {
            List<Emp> list = empService.listAllEmployee();
            req.setAttribute("empList", list);
            this.getServletContext().getRequestDispatcher("/toMain").forward(req, resp);
        } else {
            this.getServletContext().getRequestDispatcher("/page/add.jsp").forward(req, resp);
        }
    }
}
